package com.wwlwxg.handler;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wwlwxg.service.ShiroService;

import sun.print.resources.serviceui;

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private ShiroService service;
	
	@RequestMapping("/testShiroAnnotation")
	public String testShiroAnnotation(HttpSession session) {
		session.setAttribute("key", "value12345"); 
		service.testMethod();
		return "redirect:/index.jsp";
	}
	
	@RequestMapping("/login")
	public String login(@RequestParam("username") String username,
					@RequestParam("password") String password) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		// Remember me
		token.setRememberMe(true);
		try {
			currentUser.login(token);
		}catch(UnknownAccountException e) {
			log.info("----> There is no user with name of " + token.getPrincipal());
		}catch(IncorrectCredentialsException e) {
			log.info("----> Password for account " + token.getCredentials() + " is incorrected!");
		}catch(LockedAccountException e) {
			log.info("----> The account of " + token.getPrincipal() + " is locked !");
		}catch(AuthenticationException e) {
			log.info("----> error!!!!!!!!!!!!!!登陆失败!");
		}
		
		return "redirect:/index.jsp";
		
	}
}
